<template>
  <div class="app-container">

    <div id="divSearch" ref="divSearch">
      <el-form :inline="true" :model="Search" class="demo-form-inline">
        <el-form-item label="日期" prop="Search">

          <el-date-picker
            v-model="Search.CreatedOn"
            type="daterange"
            start-placeholder="开始日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '00:00:00']"
          />

        </el-form-item>
        <el-form-item label="名称" prop="Search">

          <el-input v-model.trim="Search.Name" placeholder="名称" />

        </el-form-item>
        <el-form-item>

          <el-button type="primary" icon="el-icon-search" size="small" @click="getDataList">查询</el-button>
          <el-button type="success" icon="el-icon-circle-plus" size="small" @click="handeAdd">新增</el-button>

        </el-form-item>
      </el-form>
    </div>
    <el-table :data="menulist" style="width: 100%;margin-top:30px;" border @sort-change="sortChange">
      <el-table-column align="center" label="ID" width="220">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="页面名称" width="220" sortable prop="path">
        <template slot-scope="scope">
          {{ scope.row.path }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="完整路径">
        <template slot-scope="scope">
          {{ scope.row.component }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="英文名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="标题">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="上级">
        <template slot-scope="scope">
          {{ scope.row.parentid }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="启用">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.Status"
            active-color="#13ce66"
            :active-value="1"
            :inactive-value="0"
            inactive-color="#ff4949"
          /></template>
      </el-table-column>

      </el-switch>
      <el-table-column align="center" label="Operations">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">Edit</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="sizes, prev, pager, next,total"
      :page-size="Search.pageSize"
      :total="Search.total"
      @current-change="pageChange"
    />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'创建'" width="93%" top="20px">
      <el-form :model="EditObj" label-width="80px" label-position="left">
        <el-form-item label="页面名称">
          <el-input v-model="EditObj.path" placeholder=" path" />
        </el-form-item>
        <el-form-item label="完整路径">
          <el-input
            v-model="EditObj.component"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="路径"
          />
        </el-form-item>
        <el-form-item label="英文名称">
          <el-input v-model="EditObj.name" placeholder="英文名称" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="EditObj.Status"
            active-color="#13ce66"
            :active-value="1"
            :inactive-value="0"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="标题">
          <el-input
            v-model="EditObj.title"
            type="text"
            placeholder="标题"
          />
        </el-form-item>
        <el-form-item label="上级">
          <el-input
            v-model="EditObj.parentid"
            type="text"
            placeholder="上级"
          />
        </el-form-item>
        <el-form-item label="权限">

          <el-table
            ref="multipleTable"
            :data="roles"
            tooltip-effect="dark"
            style="width: 100%;height:60%"
            height="300"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              label="ID"
              width="120"
            >
              <template slot-scope="scope">{{ scope.row.RoleID }}</template>
            </el-table-column>
            <el-table-column
              prop="RoleName"
              label="角色名"
              width="120"
            />
            <el-table-column align="header-center" label="启用">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.RoleChecked"
                  active-color="#13ce66"
                  :active-value="1"
                  :inactive-value="0"
                  inactive-color="#ff4949"
                /></template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmData">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getDataList } from '@/api/datalist'
import { updateMenu } from '@/api/menu'
// 默认的编辑字段
const defaultObject = {
  
}

export default {
  data() {
    return {
      EditObj: Object.assign({}, defaultObject),
      routes: [],
      menulist: [], // 菜单对象
      roles: [], // 权限对象
      multipleTable: [], // 编辑的时候，权限已选择
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      Search: {// 查询条件
        total: 0, // 总记录数
        pageSize: 10, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: '001', // 表编号
        jsWhere: ''// 自定义条件
      },
      Role: {// 权限查询参数
        total: 0, // 总记录数
        pageSize: 1000, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: '002', // 表编号
        jsWhere: ' AND Status=1'// 自定义条件
      },
      RoleMap: {// 权限配置参数
        total: 0, // 总记录数
        pageSize: 1000, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: '003', // 表编号
        jsWhere: ' AND Status=1'// 自定义条件
      },
      screenWidth: document.body.clientWidth
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server

    this.getDataList()
  },
  methods: {
    pageChange(page) { // 翻页
      this.Search.page = page

      this.getDataList()
    },
    async getDataList() { // 获取列表数据，通用
      const res = await getDataList({ data: JSON.stringify(this.Search) })

      this.menulist = res.data.Table
      this.Search.total = res.data.Table1[0].RecordCount
      
    },
    sortChange: function(column) {
      // column, prop, order,排序，通用
      
      this.Search.sort = column.prop + ' ' + column.order

      this.getDataList()
    },

    handeAdd() { // 新建
      this.EditObj = Object.assign({}, defaultObject)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
      this.getRoles('')
    },
    handleEdit(scope) { // 修改
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.EditObj = deepClone(scope.row)
      this.$nextTick(() => {
        const routes = this.generateRoutes(this.EditObj.routes)
        this.$refs.tree.setCheckedNodes(this.generateArr(routes))
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false
      })
      this.getRoles(this.EditObj.id)
    },
    async getRoles(menuId) { // 新建或编辑的时候读取权限
      
      const s = ' and Status=1 ' + (menuId === '' ? '' : ' AND MenuCode=\'' + menuId + '\'')
      this.RoleMap.jsWhere = s
      const roleMaps = await getDataList({ data: JSON.stringify(this.RoleMap) })
      
      const res = await getDataList({ data: JSON.stringify(this.Role) })
      const _this = this
      this.Role.total = res.data.Table1[0].RecordCount
      res.data.Table.forEach(row => {
        row.RoleChecked = 0// 默认没有配置
        roleMaps.data.Table.forEach(row2 => {
          if (row2.RoleID === row.RoleID) {
            row.RoleChecked = 1
            
          }
        })
      })
      this.roles = res.data.Table
      this.multipleTable.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row), true
      })
      
    }, toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.roles.forEach(row => {
        row.RoleChecked = 0
      })
      this.multipleSelection.forEach(row => {
        row.RoleChecked = 1
      })
    },
    async handleDelete({ $index, row }) {
      this.$confirm('确定删除该记录吗?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteRole(row.key)
          this.menulist.splice($index, 1)
          this.$message({
            type: 'success',
            message: '已删除!'
          })
        })
        .catch(err => { console.error(err) })
    },
    async confirmData() { // 提交数据，需要修改
      const isEdit = this.dialogType === 'edit'

      if (isEdit||true) {
        const result = await updateMenu({ header: JSON.stringify(this.EditObj), roles: JSON.stringify(this.roles), data: JSON.stringify(this.Search) })
        
        if (result.code === 20000) {
          const { description, key, name } = this.EditObj
          this.dialogVisible = false
          this.$notify({
            title: 'Success',
            dangerouslyUseHTMLString: true,
            message: result.message,
            type: 'success'
          })
          this.getDataList()
          this.roles = []
        } else {
          this.$notify({
            title: 'error',
            dangerouslyUseHTMLString: true,
            message: result.message,
            type: 'error'
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .EditObjs-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 5px;
  }
}
</style>
